<template>
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>

    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-form-item label="物料描述" prop="description">
          <el-input v-model="queryParams.description" placeholder="请输入物料描述"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="warning" plain icon="el-icon-download" size="mini"
                     @click="handleExport" v-hasPermi="['develop:OrderIronDetail:export']">导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
                :max-height="tableMaxHeight"  show-summary :summary-method="getSummaries" border>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" prop="sort" width="50"/>
        <el-table-column label="订单" align="center" prop="order.code"  width="80" show-overflow-tooltip/>
        <el-table-column label="名称" align="center" prop="name"  show-overflow-tooltip/>
        <el-table-column label="物料描述" align="center" prop="description" show-overflow-tooltip/>
        <el-table-column label="数量" align="center" prop="amount" width="50"/>
        <el-table-column label="单重" align="center" prop="unitWeight" width="80"/>
        <el-table-column label="总重" align="center" prop="totalWeight" width="100"/>
        <el-table-column label="核算单重" align="center" prop="calcUnitWeight" width="80"/>
        <el-table-column label="核算总重" align="center" prop="calcTotalWeight" width="80"/>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip width="80"/>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @pagination="getList"/>

      <orderIronDetail-form ref="form" @ok="getList"></orderIronDetail-form>
      <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>
    </div>
  </el-dialog>
</template>

<script>
import {accAdd,deleteAction, getAction} from '@/api/manage'
import OrderIronDetailForm from '@/views/develop/orderIronDetail/module/OrderIronDetailForm'
import UploadDialog from "@/views/upload/UploadDialog.vue";

export default {
  name: "OrderIronDetailListViewModule",
  components: {
    UploadDialog,
    OrderIronDetailForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "铁附件订单配件拆分明细",
      // 是否显示弹出层
      open: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 铁附件订单拆解明细表格数据
      dataList: [],
      recordId: null,
      orderId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        recordId: null,
        description: null,
        unit: null,
        amount: null,
        unitWeight: null,
        totalWeight: null,
        sort: null,
        params:{},
        orderByColumn:"a.sort",
        isAsc:"asc"
      },
      url: {
        list: '/orderIronDetail/orderIronDetail/list',
        remove: '/orderIronDetail/orderIronDetail/',
        export: '/orderIronDetail/orderIronDetail/export',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    /** 查询铁附件订单拆解明细列表 */
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.form.handleAdd(this.recordId,this.orderId);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(this.url.export, {
        ...this.queryParams
      }, `orderIronDetail_${new Date().getTime()}.xlsx`)
    },

    show(recordId,orderId){
      this.open = true;
      this.recordId = recordId;
      this.orderId = orderId;
      this.queryParams.recordId = recordId;
      this.getList();
    },
    showUploadDialog(){
      this.$refs.uploadDialog.title = "信息导入";
      this.$refs.uploadDialog.tmplName = "铁附件明细.xlsx";
      this.$refs.uploadDialog.fileName = "铁附件明细.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/orderIronDetail/orderIronDetail/importData?recordId="+this.recordId+"&orderId="+this.orderId;
      this.$refs.uploadDialog.show();
    },
    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" +response.data.numupdate+"条！"+ response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" +response.data.numupdate+"条！"+ response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      }
      this.getList();
    },

    colChange (newWidth, oldWidth, column, event) {
      setTimeout(() => {
        console.log(newWidth, oldWidth, column, event)
        console.log('拖动表头改变列宽')
        let applyTableColWidths = []
        let applyTable = document.getElementById('applyTable')
        let applyTableColgroup = applyTable.getElementsByTagName('colgroup')[0]
        let applyTableCol = applyTableColgroup.getElementsByTagName('col')
        for (let i = 0; i < applyTableCol.length; i++) {
          applyTableColWidths.push(applyTableCol[i].width)
        }
        console.log(applyTableColWidths)
        localStorage.setItem('applyTableColWidths', JSON.stringify(applyTableColWidths))
      }, 100)
    },
    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "amount" || column.property === "totalWeight" || column.property === "totalPrice" || column.property === "unitWeight" || column.property === "calcUnitWeight" || column.property === "calcTotalWeight" ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },






  }
};
</script>
